<template>
  <abstract-message-list-item
    class="board-list-item"
    :author-avatar-url="message.author.avatar_url"
    :author-id="message.author_id"
    :author-name="message.author.realname"
    :comment-content="message.content"
    :create-at="message.create_at"
    :update-at="message.update_at"
    @edit="promptEditMessage()"
    @remove="handleRemoveMessage()"
  >
    <template #actions>
      <mu-button icon @click="clickMessage(message.author_id)">
        <mu-icon value="chat_bubble"></mu-icon>
      </mu-button>
    </template>
  </abstract-message-list-item>
</template>

<script>
import AbstractMessageListItem from '@/components/AbstractMessageListItem'
import api from '@/api'

export default {
  name: 'BoardListItem',
  components: {
    AbstractMessageListItem
  },
  props: {
    message: {
      type: Object,
      required: true
    }
  },
  methods: {
    // 提示撤销留言
    handleRemoveMessage() {
      this.$confirm('确定要撤销？', '提示', {
        type: 'warning'
      }).then(({ result }) => {
        if (result) {
          this.removeMessage()
        } else {
          this.$toast.message('已取消')
        }
      })
    },
    // 撤销留言
    async removeMessage() {
      try {
        await api.removeBoardMessage(this.message.id)
        this.$toast.success('撤销成功')
        this.$emit('refresh')
      } catch (err) {
        this.$apiCatch(err)
      }
    },
    // 提示输入留言
    promptEditMessage() {
      this.$prompt('请输入新的留言内容', '提示', {
        inputValue: this.message.content,
        validator(value) {
          if (!value || value.length <= 0) {
            return {
              valid: false,
              message: '内容不能为空'
            }
          } else if (value.length > 500) {
            return {
              valid: false,
              message: '内容不能太长（500字）'
            }
          } else {
            return {
              valid: true
            }
          }
        }
      }).then(({ result, value }) => {
        if (result) {
          this.editMessage(value)
        } else {
          this.$toast.message('已取消')
        }
      })
    },
    // 编辑留言
    async editMessage(content) {
      try {
        await api.editBoardMessage(this.message.id, content)
        this.$toast.success('编辑成功')
        this.$emit('refresh')
      } catch (err) {
        this.$apiCatch(err)
      }
    },
    // 给某人发私信
    clickMessage(userId) {
      this.$router.push({
        name: 'message-private-chat',
        params: {
          id: userId
        }
      })
    }
  }
}
</script>

<style scoped>
.tags {
  padding: 0 16px;
}
.tag-badge + .tag-badge {
  margin-left: 4px;
}
.is-phone .tags {
  padding: 0 8px;
}
</style>
